const db = wx.cloud.database()
var util = require('../../utils/util.js')
Page({
  data: {
    TabCur: 0,
    navTab: ['正在进行的投票', '已经结束的投票'],
    votelist: [],
  },

  LoadAvailablevote(){
    wx.showLoading({
      title: '数据加载中...',
    })
    db.collection('vote').where({
      available: true
    }).orderBy('submitdate', 'desc')
      .get().then(res => {
        for (var index in res.data) {
          res.data[index].time = util.formatTime(res.data[index].submitdate)
          res.data[index].deadtime = util.formatTime(res.data[index].deadline)
          res.data[index].btnText = '投票'
        }
        this.setData({
          votelist: res.data
        })
        wx.hideLoading()
      })
  },
  
  LoadUnavailablevote() {
    wx.showLoading({
      title: '数据加载中...',
    })
    db.collection('vote').where({
      available: false
    }).orderBy('submitdate', 'desc')
      .get().then(res => {
        for (var index in res.data) {
          res.data[index].time = util.formatTime(res.data[index].submitdate)
          res.data[index].deadtime = util.formatTime(res.data[index].deadline)
          res.data[index].btnText = '查看'
        }
        this.setData({
          votelist: res.data
        })
        wx.hideLoading()
      })
  },

  onShow: function () {
    if (this.data.TabCur == 0) {
      this.LoadAvailablevote()

    } else if (this.data.TabCur == 1) {
      this.LoadUnavailablevote()
    }
  },

  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id
    })
    if (this.data.TabCur == 0) {
      this.LoadAvailablevote()

    } else if (this.data.TabCur == 1) {
      this.LoadUnavailablevote()
    }
  },
  gotovote: function (event) {
    var userInfo = wx.getStorageSync('userInfo');
    if (userInfo == "") {
      wx.navigateTo({
        url: '../auth/auth'
      })
      return
    }   
    wx.navigateTo({
      url: '../votedetail/votedetail?id=' + event.currentTarget.dataset.id
    })
  }
})